package com.aurora.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.aurora.common.constant.CartConstant;
import com.aurora.common.utils.R;
import com.aurora.gulimall.cart.feign.ProductFeignService;
import com.aurora.gulimall.cart.interceptor.CartInterceptor;
import com.aurora.gulimall.cart.service.CartService;
import com.aurora.gulimall.cart.vo.Cart;
import com.aurora.gulimall.cart.vo.CartItem;
import com.aurora.gulimall.cart.vo.SkuInfoVo;
import com.aurora.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    /**添加到购物车
     * @param skuId
     * @param num
     * @return
     */
    @Override
    public CartItem addToCart(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = new CartItem();
        String res = (String) cartOps.get(skuId.toString());
        if(StringUtils.isEmpty(res)){//购物车没有此商品
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1、远程查询要添加的商品信息
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                //2、商品添加到购物车
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(data.getPrice());
            },threadPoolExecutor);
            //3、远程查询sku组合信息
            CompletableFuture<Void> getSkuSaleAttrValuesTask = CompletableFuture.runAsync(() -> {
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            },threadPoolExecutor);
            getSkuInfoTask.runAfterBothAsync(getSkuSaleAttrValuesTask,()->{
                cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            },threadPoolExecutor);
            //CompletableFuture.allOf()
            return cartItem;
        }else{
            CartItem item = JSON.parseObject(res, CartItem.class);
            item.setCount(item.getCount()+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(item));
            return item;
        }

    }

    /**根据id获取当前添加到购物车的商品信息
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String item = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(item, CartItem.class);
        return cartItem;
    }

    /**获取购物车
     * @return
     */
    @Override
    public Cart getCart() {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId() != null){//登录
            List<CartItem> tempCartItems = getCartItems(CartConstant.CART_PREFIX + userInfoTo.getUserKey());
            if(tempCartItems != null){
                //临时购物车有数据，需要合并
                tempCartItems.stream().forEach(cartItem -> {
                    addToCart(cartItem.getSkuId(),cartItem.getCount());
                });
                //清除临时购物车数据
                clearCart(CartConstant.CART_PREFIX+userInfoTo.getUserKey());

            }
            //获取登录后的购物车  包含临时购物车数据
            String userKey = CartConstant.CART_PREFIX+userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(userKey);
            cart.setItems(cartItems);

        }else{//获取临时购物车
            String userKey = CartConstant.CART_PREFIX+userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(userKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    /**
     * 清空购物车
     */
    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    /**根据勾选状态修改redis
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    /**改变购物车商品数量
     * @param skuId
     * @param num
     */
    @Override
    public void changeItemCount(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    /**订单确认-获取当前用户选中的购物车项
     * @return
     */
    @Override
    public List<CartItem> getCurrentUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        List<CartItem> cartItems = getCartItems(CartConstant.CART_PREFIX+userInfoTo.getUserId());
        List<CartItem> collect = cartItems.stream()
                .filter(cartItem -> cartItem.getCheck())
                .map(cartItem -> {
                    //更新购物车价格
                    BigDecimal price = productFeignService.getPrice(cartItem.getSkuId());
                    cartItem.setPrice(price);
                    return cartItem;
                })
                .collect(Collectors.toList());
        return collect;
    }

    /**获取要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if(userInfoTo.getUserId() != null){//用户已登录
            cartKey = CartConstant.CART_PREFIX+userInfoTo.getUserId();
        }else{
            cartKey = CartConstant.CART_PREFIX+userInfoTo.getUserKey();
        }
        //绑定redis操作对象
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }

    /**根据指定cartKey获取购物车数据
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();
        if(values != null && values.size()>0){
            List<CartItem> cartItems = values.stream().map(item -> {
                return JSON.parseObject((String) item, CartItem.class);
            }).collect(Collectors.toList());
            return cartItems;
        }
        return null;
    }


}
